package com.lightsh.util;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import com.google.android.maps.GeoPoint;

import android.content.Context;
import android.net.wifi.ScanResult;
import android.telephony.NeighboringCellInfo;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
import android.util.Log;

public class Utility {
	private static final String TAG = "Utility";
	private static final boolean DEBUG = true;
	
	/**
	 * 获取手机sim的基站信息.
	 * 信息以json对象的形式返回,内容形如:
	 * {"cell_towers":[{"cell_id":25070, "location_area_code":4474,"mobile_country_code":460,"mobile_network_code":0},{}]}
	 * @param context 窗口的上下文
	 * @return 返回json结果，如果获取失败返回null
	 */
	private static final JSONObject getCellTowers(Context context){
		
		try{
			TelephonyManager teleManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
			GsmCellLocation gcl = (GsmCellLocation) teleManager.getCellLocation();
			int cid = gcl.getCid();
			int lac = gcl.getLac();
			ArrayList<NeighboringCellInfo> neighCelInfoList = (ArrayList<NeighboringCellInfo>) teleManager.getNeighboringCellInfo();
			int mcc = Integer.valueOf(teleManager.getNetworkOperator().substring(0, 3));
			int mnc = Integer.valueOf(teleManager.getNetworkOperator().substring(3, 5));
			
			JSONObject resultObj = new JSONObject();
			JSONArray array = new JSONArray();
			JSONObject data = new JSONObject();
			data.put("cell_id", cid); // 25070
			data.put("location_area_code", lac);// 4474
			data.put("mobile_country_code", mcc);// 460
			data.put("mobile_network_code", mnc);// 0
			array.put(data);
			for (int i = 0; i < neighCelInfoList.size(); ++i) {
				data = new JSONObject();
				data.put("cell_id", neighCelInfoList.get(i).getCid()); // 25070
				data.put("location_area_code", neighCelInfoList.get(i).getLac());// 4474
				data.put("mobile_country_code", mcc);// 460
				data.put("mobile_network_code", mnc);// 0
				array.put(data);
			}			
			resultObj.put("cell_towers", array);
			return resultObj;
		}catch(Exception e) {
			if(DEBUG){
				e.printStackTrace();
			}
			return null;
		}
	}
	
	/**
	 * 获取手机附近wifi的MAC码信息.
	 * 信息以json对象的形式返回,内容形如:
	 * {"cell_towers":[{"mac_address":AFG022345235, "signal_strength":4474},{}]}
	 * @param context 窗口的上下文
	 * @return 返回json结果;如果获取失败或者附近没有wifi信息,则返回null
	 */
	private static final JSONObject getWifiInfo(List<ScanResult> wifiList){
		
		try{
			JSONObject resultObj = null;
			JSONArray array = new JSONArray();
			JSONObject data = new JSONObject();
			if(wifiList != null && !wifiList.isEmpty()){
				resultObj = new JSONObject();
				for(int i = 0 ; i < wifiList.size(); ++i){
					data = new JSONObject();
					data.put("mac_address", wifiList.get(i).BSSID);
					data.put("signal_strength", wifiList.get(i).level);
					array.put(data);
				}
				resultObj.put("wifi_towers", array);
			}
			return resultObj;
		}catch(Exception e) {
			if(DEBUG){
				e.printStackTrace();
			}
			return null;
		}
	}
	
	public static final GeoPoint getLocationByCellAndWifi(Context context, List<ScanResult> wifiList){
		
		try{
			JSONObject holder = new JSONObject();
			holder.put("version", "1.1.0");
			holder.put("host", "maps.google.com");
			// holder.put("address_language", "zh_CN");
			holder.put("request_address", true);
			
			boolean bHasInfo = false;
			if(context != null){
				JSONObject cellJson = Utility.getCellTowers(context);
				if(cellJson != null){
					holder.put("cell_towers", cellJson.getJSONArray("cell_towers"));
					bHasInfo = true;
				}
			}
			if(wifiList != null && !wifiList.isEmpty()){
				JSONObject wifiJson = Utility.getWifiInfo(wifiList);
				if(wifiJson != null){
					holder.put("wifi_towers", wifiJson.getJSONArray("wifi_towers"));
					bHasInfo = true;
				}
			}
			
			if(!bHasInfo){
				return null;
			}
			
			DefaultHttpClient client = new DefaultHttpClient();
			HttpPost post = new HttpPost("http://www.google.com/loc/json");

			StringEntity se = new StringEntity(holder.toString());
			post.setEntity(se);
			HttpResponse response = client.execute(post);			
			HttpEntity entity = response.getEntity();
			String responseString = new String(EntityUtils.toByteArray(entity), "utf-8");
			JSONObject resultObject = new JSONObject(responseString);
			JSONObject locationObject = resultObject.getJSONObject("location");
			double latitude = locationObject.getDouble("latitude");
			double longitude = locationObject.getDouble("longitude");

			return new GeoPoint((int) (latitude * 1e6), (int) (longitude * 1e6));
			
		}catch(Exception e){
			if(DEBUG){
				e.printStackTrace();
			}
		}
		return null;
	}
}
